//
//  RegistUserViewController.m
//  PatientApp
//
//  Created by chirui on 2017/5/17.
//  Copyright © 2017年 Shui. All rights reserved.
//

#import "RegistUserViewController.h"
#import "RegistMessageViewController.h"
//#import "SHNavigationController.h"

@interface RegistUserViewController ()
@property (weak, nonatomic) IBOutlet UIView *phoneView;
@property (weak, nonatomic) IBOutlet UIView *codeView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UIView *surePasswordView;
@property (weak, nonatomic) IBOutlet UITextField *phoneText;
@property (weak, nonatomic) IBOutlet UITextField *codeText;
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@property (weak, nonatomic) IBOutlet UITextField *passwordText;
@property (weak, nonatomic) IBOutlet UITextField *surePasswordYext;
@property (weak, nonatomic) IBOutlet UIButton *okBtn;
@property (weak, nonatomic) IBOutlet UIButton *sureBtn;

@property (nonatomic,copy) NSString * typeStr;

@end

@implementation RegistUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    TitleView(@"注册");
    
    _typeStr = @"1";
    
    self.okBtn.selected = YES;
    self.sureBtn.layer.cornerRadius = 45/2.f;
    self.sureBtn.layer.masksToBounds = YES;
    
    
    
    //    self.codeBtn.layer.cornerRadius = 22.f;
    //    self.codeBtn.layer.masksToBounds = YES;
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_public_return" target:self action:@selector(backButton)];
}

-(void)backButton {
        
        [self.navigationController popViewControllerAnimated:YES];
}


- (IBAction)backClick:(UIButton *)sender {
    
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)layerCornerRadiusView:(UIView *)view {
    
    view.layer.cornerRadius = 22.5f;
    view.layer.masksToBounds = YES;
    view.layer.borderWidth = 0.5;
    view.layer.borderColor = [UIColor grayColor].CGColor;
}

- (IBAction)codeBtnClick:(UIButton *)sender {
    
    if ([SHJudgeTools valiMobile:self.phoneText.text] != nil) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.yOffset = 100.f;
        hud.labelText = [SHJudgeTools valiMobile:self.phoneText.text];
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:0.5];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [hud removeFromSuperview];
        });
        return;
    }
    
    [self sendMSNetWorkingFor];
    __block int timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=1){
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
              
                [self.codeBtn setTitle:@"获取" forState:UIControlStateNormal];
                self.codeBtn.userInteractionEnabled = YES;
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString  * time = [NSString stringWithFormat:@"%d(秒)",timeout];
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [self.codeBtn setTitle:time forState:UIControlStateNormal];
                [UIView commitAnimations];
                self.codeBtn.userInteractionEnabled = NO;
            
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}
- (IBAction)okBtnClick:(UIButton *)sender {
    
    self.okBtn.selected = !self.okBtn.selected;
    
    if (self.okBtn.isSelected) {
        
        _typeStr = @"1";
    }else {
    
        _typeStr = @"0";
    }
    
}
- (IBAction)userMessage:(UIButton *)sender {
    
    RegistMessageViewController * message =[[RegistMessageViewController alloc]init];
    
   [self.navigationController pushViewController:message animated:YES];
    
}
- (IBAction)sureBtnClick:(UIButton *)sender {
    
    
    if ([SHJudgeTools valiMobile:self.phoneText.text] != nil) {
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.margin = 10.f;
        hud.yOffset = 100.f;
        hud.labelText = [SHJudgeTools valiMobile:self.phoneText.text];
        hud.removeFromSuperViewOnHide = YES;
        [hud hide:YES afterDelay:0.5];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [hud removeFromSuperview];
        });
        return;
    }else if (self.phoneText.text.length!=11) {
        
        [SHJudgeTools MBProgressHUDPromptWith:@"手机号码不正确" On:self.view];
        return;
        
    }else if(_codeText.text.length<1){
        
        [SHJudgeTools MBProgressHUDPromptWith:@"验证码不能为空" On:self.view];
        return;
        
    }else if(_passwordText.text.length<6){
        [SHJudgeTools MBProgressHUDPromptWith:@"密码不能少于6位" On:self.view];
        return;
    }else if (![_passwordText.text isEqualToString:_surePasswordYext.text]){
        
        [SHJudgeTools MBProgressHUDPromptWith:@"两次密码不一致" On:self.view];
        return;
        
    }else if ([_typeStr isEqualToString:@"0"]){
        
        [SHJudgeTools MBProgressHUDPromptWith:@"请勾选同意用户协议" On:self.view];
        return;
        
    } else{
        
        [self registerNetWorking];
    }

}

#pragma mark  网络请求


-(void)registerNetWorking {
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",NetWorkAddress_api,regist_applyFor_api];
    
    
    NSDictionary * dic = @{@"phone":_phoneText.text,
                           @"password":_passwordText.text,
                           @"code":_codeText.text,
                           @"coord":[NSString stringWithFormat:@"%@,%@",USER_DEFAULTGet(@"lon"),USER_DEFAULTGet(@"lat")]
                           };
    
     [MBProgressHUD showMessag:@"正在注册..." withDelay:0 toView:self.view withMode:MBProgressHUDModeIndeterminate hideWithDelay:0];
    [PostNetWorking postNetWorkingStr:parametersStr andparameters:dic Success:^(id responseObject) {
      [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] intValue]==200) {
            
            [MBProgressHUD showMessag:@"注册成功" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW , (1 * NSEC_PER_SEC)), dispatch_get_main_queue(),^{
                    
                    [self.navigationController popViewControllerAnimated:YES];
                });
            });
            
        } else {
            
            [MBProgressHUD showMessag:responseObject[@"mark"] withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
        }
        
    } failed:^(NSError *error) {
        NSLog(@"ERROR ==%@",error);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showMessag:@"网络错误" withDelay:0 toView:self.view withMode:MBProgressHUDModeText hideWithDelay:1.5];
    }];
    
}

// 验证码
-(void)sendMSNetWorkingFor{
    
    NSString * parametersStr = [NSString stringWithFormat:@"%@%@",NetWorkAddress_api,smsSend_regist_api];
    NSDictionary * parameter = @{@"phone":_phoneText.text,
                                 };
    NSLog(@"param ==%@",parameter);
    
    SHuiMBhubNoTimeStr(@"正在发送");
    [PostNetWorking postNetWorkingStr:parametersStr  andparameters:parameter  Success:^(id responseObject) {
        SHuiMBHidleYes;
        if ([responseObject[@"code"] intValue]==200) {
            SHuiMBhudTextTimeStr(@"发送成功");

        } else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
   
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"请检查您的网络!");
    }];
}







- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
